#include <stdio.h>
#include <string.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>

int Create_socket(int port)
{
    int ret = 0;
    int sock_fd = -1;
    /*创建套接字*/
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == sock_fd)
    {
        printf("socket faild,err:%s\n", strerror(errno));
        return -1;
    }
    //设置端口复用
    int opt = 1;
    setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,(const void *) &opt,sizeof(opt));
    /*绑定地址*/
    struct sockaddr_in sock_addr;
    sock_addr.sin_family = AF_INET;
    sock_addr.sin_port = htons(port);
    sock_addr.sin_addr.s_addr = INADDR_ANY;
    ret = bind(sock_fd, (struct sockaddr*)&sock_addr, sizeof(struct sockaddr_in));
    if(ret < 0)
    {
        printf("bind Error:%m\n");
        close(sock_fd);
        sock_fd = -1;
        return -1;
    }
    return sock_fd;
}
int Do_Connect_socket(int sock_fd,char* srv_ip,int srv_port)
{
    //连接server端的ip和port
    struct sockaddr_in sock_server;
    sock_server.sin_port = htons(srv_port);
    sock_server.sin_addr.s_addr = inet_addr(srv_ip);
    sock_server.sin_family = PF_INET;
    memset(sock_server.sin_zero,0,8);
    int ret = connect(sock_fd,(struct sockaddr *)&sock_server,sizeof(struct sockaddr));
    if(-1 == ret)
    {
        close(sock_fd);
        printf(" connect faild,err:%s\n", strerror(errno));
        return -1;
    }

    return ret;
}
int main()
{
  //  char buff[] = {0x02,0x10,0x00,0x34,0x00,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x36,0x39,0x34,0x38,0x31,0x32,0x32,0x30,0x30,0x31,0x35,0x38,0x31,0x32,0x34,0x33,0x43,0x31,0x36,0x41,0x33,0x33,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x20,0x20,0x37};
    char buff[] = {"hello"};
    int fd1=0,fd2=0,fd3,fd4,fd5;
    fd1=Create_socket(0);
    fd2=Create_socket(0);
    fd3=Create_socket(0);
    fd4=Create_socket(0);
    fd5=Create_socket(0);

    Do_Connect_socket(fd1,"192.168.4.224",55560);
    Do_Connect_socket(fd2,"192.168.4.224",55560);
    Do_Connect_socket(fd3,"192.168.4.224",55560);
    Do_Connect_socket(fd4,"192.168.4.224",55560);
    Do_Connect_socket(fd5,"192.168.4.224",55560);

	write(fd1,buff,sizeof(buff));
//	write(fd2,buff,sizeof(buff));
//	write(fd3,buff,sizeof(buff));
//	write(fd4,buff,sizeof(buff));
//	write(fd5,buff,sizeof(buff));

    int rd_no = read(fd1,buff,sizeof(buff));
    printf("===read %d\n",rd_no);

    sleep(1000);
    return 0;
}
